package cn.shiwei.hr.consume;

import cn.shiwei.hr.repository.AssertUtil;
import cn.shiwei.hr.to.TempOrderTo;
import com.netflix.discovery.converters.Auto;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static cn.shiwei.hr.constants.KillCourseConstants.SIGNAL_KEY;
import static cn.shiwei.hr.constants.MessageConstants.QUEUE_DEAD;

@Component
@Slf4j
public class KillConsume {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @RabbitListener(queues = QUEUE_DEAD ,containerFactory = "rabbitListenerContainerFactory")
    public void consumerSMS(String redisKey, Channel channel, Message message){
        // 到达消费者的, 消息(订单号), 表示已经超过设定时间(设置的是 5 秒, 具体应该设置为 30 min)
        // 消息过期, 先检查redis中有没有对应的订单, 有表明为用户订单超时, 未支付
        // 非空判断
        AssertUtil.stringIsEmpty(redisKey, "错误的消息");
        log.info("订单疑似超时, 记录: {}", redisKey);

        // 查询redis
        TempOrderTo tempOrderTo = (TempOrderTo) redisTemplate.opsForValue().get(redisKey);
        if (tempOrderTo != null) {
            // redis中的临时订单不为空, 临时删除订单
            redisTemplate.delete(redisKey);
            // 回退库存(信号量)
            redissonClient.getSemaphore(String.format(SIGNAL_KEY, tempOrderTo.getKillCourseId().toString())).release(1);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
